package com.hare.auth.exception;


import com.alibaba.fastjson.JSONObject;
import com.hare.common.global.constant.BaseConstant;
import com.hare.common.global.enums.ResultCode;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @program: Hare
 * @description: 认证失败处理类 返回未授权
 * @author: Hare
 * @create: 2022-07-04 20:34
 * @Version 6.0.1
 **/
@Component
public class FailAuthenticationEntryPoint implements AuthenticationEntryPoint {


    /**
     * 认证失败处理
     *
     * @param request
     * @param response
     * @param e
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
        String message = String.format("认证失败,请重新登录");
        response.setStatus(200);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        Map<String, Object> result = new HashMap<>();
        result.put("success", BaseConstant.ERROR_BON);
        result.put("code", ResultCode.UNAUTHORIZED.getCode());
        result.put("message", message);
        result.put("data", "token无效或过期,请重新登录");
        response.getWriter().write(JSONObject.toJSONString(result));
    }
}
